<?php
/**
 * Class Agent
 * Desc  代理Controller
 * Create on 2021/8/26 14:12
 * Create by wangyafang
 */

namespace app\api\controller\xyb;

use addons\xyb\XypHelper;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\api\model\xyb\Order;
use app\api\model\xyb\OrderComplaint;
use app\api\model\xyb\Profit;
use app\api\model\xyb\UsersAppeal;
use app\api\model\xyb\Wallets;
use app\api\service\OrdersService;
use app\api\service\UsersService;
use app\common\model\xyb\AdminBelong;
use app\common\model\xyb\UserBelong;
use app\api\model\xyb\OrderReceive;
use app\api\model\xyb\UserReceiveApply;
use app\api\model\xyb\UserReceive;
use app\api\model\xyb\UserPlat;
use app\api\model\xyb\UserWechat;
use think\Db;

class Agent extends Base
{
    protected $model = '';
    protected $noNeedLogin = [''];

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\api\model\xyb\Agent();
    }
    /**
     * desc:代理个人中心
     */
    public function center()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $order_model = (new \app\api\model\xyb\Order());
        $receive_apply_model = (new \app\api\model\xyb\UserReceiveApply());

        $users = $this->getAuthUsers();
        $agent_info = (new AdminBelong())->where('bind_agent_user_id',$users->id)->find();
        $agent_id = (int)$agent_info->admin_id;

        $response = [
            'order' => ['pending' => 0, 'after_sales' => 0, 'today' => 0, 'total' => 0],
            'staff' => ['total' => 0, 'pending' => 0, 'audited' => 0],
            'agent' => [
                'agent_phone'   => $agent_info->phone,
                'agent_area'    => $agent_info->agent_area,
            ]
        ];

        $response['order']['pending'] = $order_model->where(['agent_id' => $agent_id, 'status' => 1])->count();

        $response['order']['after_sales'] = 0;

        $response['order']['today'] = $order_model->where(['agent_id' => $agent_id])->whereTime('createtime', 'today')->count();

        $response['order']['total'] = $order_model->where(['agent_id' => $agent_id])->count();

        $response['staff']['total'] = $receive_apply_model->where(['agent_id'=>$agent_id])->count();
        $response['staff']['pending'] = $receive_apply_model->where(['agent_id'=>$agent_id, 'status'=>0])->count();
        $response['staff']['audited'] = $receive_apply_model->where(['agent_id'=>$agent_id, 'status'=>1])->count();

        $this->success('请求成功', $response);
    }

    /**
     * desc:订单列表
     *
     * （全部：0；待接单：1；待取件：2；待派送：8；已送达：7；已完成：3）
     */
    public function order()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $agent_info = (new AdminBelong())->where('bind_agent_user_id', $users->id)->find();
        $agent_id = (int)$agent_info->admin_id;

        $order_model = (new \app\api\model\xyb\Order());
        $where = [ 'agent_id'=>$agent_id];
        $param = $this->request->param();
        if(isset($param['status']) && $param['status']){
            $map['status'] = intval($param['status']);
        } else {
            $map['status'] = array('in',[1, 2, 3, 7, 8]);
        }
        $count = $order_model->where($where)->where($map)->count();
        $data = $order_model->where($where)
            ->where($map)
            ->alias('order')
            ->order('id desc')
            ->page($param['page'], $param['limit'])
            ->with(['user'])
            ->field("order.id,order.information,start,destination,hope_arrive,receive_id,
            type,total_fee,createtime,type,user_id,status,agent_id,mobile")
            ->select();

        foreach ($data as $k => $v) {
            $push_users = UsersService::getUsersFoundation($v['user_id']);
            $data[$k]['nickname'] = $push_users['nickname'];
            $data[$k]['avatar'] = $push_users['avatar'];
            $data[$k]['dateline_create_date'] = XypHelper::xyb_dateline($v['createtime']);//创建时间
            $data[$k]['receive_users'] = UsersService::getReceivingUsersFoundation($v['receive_id'], $v['agent_id']);
            $data[$k]['income'] = OrdersService::CalculateOrdersRevenueProportion($v['total_fee'], $v['agent_id'], $v['type']);
            /*处理状态信息*/
            $data[$k]['status_text'] = OrdersService::formatOrdersStatus($v['status']);
        }
        $this->success('请求成功',['count'=>$count,'data'=>$data]);
    }

    /**
     * desc:申请列表
     */
    public function apply()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $agent_info = (new AdminBelong())->where('bind_agent_user_id', $users->id)->find();
        $agent_id = (int)$agent_info->admin_id;
        $param = $this->request->param();
        if(isset($param['status']) && $param['status']){
            $status_map = [1=>0, 2=>-1, 3=> 1];
            $map['status'] = $status_map[$param['status']];
        } else {
            $map['status'] = array('in', [0, -1, 1]);
        }
        $receive_model = (new UserReceiveApply());
        $total = $receive_model->where($map)->where(['agent_id'=>$agent_id])->count();
        $data = $receive_model->where($map)->where(['agent_id'=>$agent_id])->order('id desc')
            ->page($param['page'], $param['limit'])
            ->select();

        foreach ($data as $k => $v) {
            $push_users = UsersService::getUsersFoundation($v['user_id']);
            $data[$k]['nickname'] = $push_users['nickname'];
            $data[$k]['avatar'] = $push_users['avatar'];
            $data[$k]['createtime'] = date('Y-m-d', $v['createtime']);
            $data[$k]['student_positive_image'] = XypHelper::stringToArray($v['student_positive_image']);
            $data[$k]['life_image'] = XypHelper::stringToArray($v['life_image']);
        }
        $this->success('请求成功',['total'=>$total, 'data'=>$data]);
    }

    /**
     * desc:审核骑手
     */
    public function examine(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        if(!$user_id = ((int)$this->request->param('user_id'))){
            $this->error('参数错误');
        }
        if(!$status = ((int)$this->request->param('status'))){
            $this->error('参数错误');
        }
        $reject_reason = $this->request->param('reject_reason','');
        if(!in_array($status, [1, 2])){
            $this->error('参数错误');
        }
        if($status == 2 && !$reject_reason){
            $this->error('请填写拒绝理由');
        }
        Db::startTrans();
        $receive_model = (new UserReceiveApply());
        $receive_apply_info = $receive_model->where(['id'=>$user_id])->find();
        if(((int)$receive_apply_info->status) != 0){
            $this->error('审核状态错误');
        }
        $receive_apply_info->status = ($status == 2 ? -1 : 1);
        if($status == 2){
            $receive_apply_info->reject_reason = $reject_reason;
        }
        $receive_apply_info->updatetime = time();
        if(!$receive_apply_info->save()){
            Db::rollback();
            $this->error('审核失败');
        }
        if($status == 1){
            (new \app\admin\model\xyb\UserReceive())->save([
                'agent_id'=>$receive_apply_info->agent_id,
                'user_id'=>$receive_apply_info->user_id,
                'app_plat'=>'MP-WEIXIN',
            ]);
        }
        Db::commit();
        $this->success('审核成功');
    }

    /**
     * desc:骑手列表
     */
    public function rider()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $agent_info = UsersService::getCommunityWhereUsersLocated($users->id);
        $param = $this->request->param();
        $status = '';
        $receive_model = (new UserReceiveApply());
        $where = ['agent_id'=>$agent_info->agent_id, 'status'=>1];
        if($stated = request()->param('stated', 0)){
            if($stated == 3){
                $where['stated'] = 2;
            } else {
                $where['presence'] = $stated;
            }
        }
        $total = $receive_model->where($where)->count();
        $data = $receive_model->where($where)->order('id desc')->page($param['page'], $param['limit'])->select();
        $profitModel = new Profit();
        $orderModel = new Order();
        foreach ($data as $k => $v) {
            $where = ['receive_id' => array('eq', $v->user_id)];
            $push_users = UsersService::getUsersFoundation($v['user_id']);
            $data[$k]['nickname'] = $push_users['nickname'];
            $data[$k]['avatar'] = $push_users['avatar'];
            $data[$k]['createtime'] = date('Y-m-d', $v['createtime']);
            $data[$k]['total_income'] = $profitModel->where($where)->sum('receive_profit');
            $data[$k]['order_num'] = $orderModel->where($where)->where('status','in',[2,3,7,8])->count();
            $data[$k]['agent_income'] = $profitModel->where($where)->sum('agent_profit');
            $data[$k]['student_positive_image'] = XypHelper::stringToArray($v['student_positive_image']);
            $data[$k]['blacklist_picture'] = XypHelper::stringToArray($v['blacklist_picture']);
            $data[$k]['life_image'] = XypHelper::stringToArray($v['life_image']);
            $data[$k]['presence'] = (intval($v['presence']) === 1);
          //  $data[$k]['stated'] = (intval($v['stated']) === 1);
            $data[$k]['bad_order_count'] = $orderModel->where($where)->where('status',3)->where('evaluate_time','>', 0)->where('evaluate', '<', 4)->count();;
        }
        $this->success('请求成功',[
            'total'     => $total,
            'data'      => $data,
            'income'    => $profitModel->where(['agent_id'=>$agent_info->agent_id])->sum('agent_profit')
        ]);
    }

    public function rider_status(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $receive_model = (new UserReceiveApply());
        $stated = $this->request->param('stated','');
        if(!$user_id = $this->request->param('user_id','')){
            $this->error('参数错误');
        }
        $blacklist_reason = $this->request->param('blacklist_reason','');
        $blacklist_picture = $this->request->param('blacklist_picture','');
        $users = $this->getAuthUsers();
        $agent_info = UsersService::getCommunityWhereUsersLocated($users->id);
        $receive = $receive_model->where(['agent_id'=>$agent_info->agent_id, 'user_id'=>$user_id])->find();
        $receive->blacklist_reason = $blacklist_reason;
        $receive->blacklist_picture = $blacklist_picture;
        $receive->stated = (int)$stated;
//        if( $receive->stated == 2){
//            if(!$blacklist_reason){
//                $this->error('请填写拉黑理由');
//            }
//
//        } else {
//            $receive->blacklist_reason = '';
//            $receive->blacklist_picture = '';
//        }
        $receive->updatetime = time();
        $receive->save();
        $this->success('操作成功');
    }

    public function complaint(){
        $users = $this->getAuthUsers();
        $agent_info = UsersService::getCommunityWhereUsersLocated($users->id);
        $status = $this->request->param('status', 0);
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $field = [
            'xyb_order.id','xyb_order.user_id','xyb_order.receive_id','xyb_order.order_no','xyb_order.mobile',
            'xyb_order.type', 'xyb_order.information','xyb_order.total_fee','xyb_order.agent_id',
            'xyb_order.annex_information_images','xyb_order.agent_id','xyb_order.agent_id',
            'yx_xyb_order_complaint.status', 'yx_xyb_order_complaint.content','yx_xyb_order_complaint.picture',
            'yx_xyb_order_complaint.tags', 'yx_xyb_order_complaint.reply_content', 'yx_xyb_order_complaint.reply_time',
            'yx_xyb_order_complaint.reply_picture','yx_xyb_order_complaint.reject_reason'
        ];
        $query = OrderComplaint::join('xyb_order','yx_xyb_order_complaint.order_id = xyb_order.id')
            ->field($field)
            ->where('xyb_order.agent_id', $agent_info->agent_id)
            ->where('xyb_order.is_complaint', 1);
        if($status){
            $query->where('yx_xyb_order_complaint.status', ($status - 1));
        } else {
            $query->where('yx_xyb_order_complaint.status', 'in', [0,1,2]);
        }
        $query->page($page, $limit)->order('yx_xyb_order_complaint.id','desc');

        $lists = $query->select();
        $count = $query->count();
        foreach ($lists as $k=>$v) {
            $push_users = UsersService::getUsersFoundation($v['user_id']);
            $lists[$k]['dateline_create_date'] = XypHelper::xyb_dateline($v['createtime']);//创建时间
            $lists[$k]['receive_users'] = new \ArrayObject();
            $lists[$k]['nickname'] = $push_users['nickname'];
            $lists[$k]['avatar'] = $push_users['avatar'];
            $lists[$k]['annex_information_images'] = XypHelper::stringToArray($v['annex_information_images']);
            $lists[$k]['picture'] = XypHelper::stringToArray($v['picture']);
            $lists[$k]['reply_picture'] = XypHelper::stringToArray($v['reply_picture']);
            $lists[$k]['type_text'] = Order::getTypeNameTextName($k['type'],[]);
            $lists[$k]['status_text'] = OrdersService::formatOrdersStatus($v['status']);
            $lists[$k]['express'] = !empty($k['express']) ? json_decode($k['express']) : [];
            if($v['receive_id']){
                $lists[$k]['receive_users'] = UsersService::getReceivingUsersFoundation($v['receive_id'],$v['agent_id']);
            }
        }
        $this->success('请求成功',['total'=>$count,'data'=>$lists]);
    }

    public function complaint_submit(){
        $users = $this->getAuthUsers();
        $agent_info = UsersService::getCommunityWhereUsersLocated($users->id);
        $order_id = $this->request->param('id', 0);
        $content = $this->request->param('content', '');
        $picture = $this->request->param('picture', '');
        $status = $this->request->param('status', 1);
        $reject_reason = $this->request->param('reject_reason', '');
        $order = Order::where('id', $order_id)->find();
        $res = OrderComplaint::submitComplaintReply($order, $content, $picture,$status, $reject_reason);
        $this->success('处理成功');
    }

    public function appeal(){
        $users = $this->getAuthUsers();
        if(!$agent_info = UsersService::getCommunityWhereUsersLocated($users->id)){
            $this->error('请先绑定社区');
        }

        $status = $this->request->param('status', 0);
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $fields = 'id,content,picture,reply_content,reply_time,status,reply_picture,users_id';
        $query = UsersAppeal::field($fields)->where('agent_id', $agent_info->agent_id);
        if($status){
            if($status == 2){
                $query->where('status', 'in', [1,2]);
            } else {
                $query->where('status', 0);
            }
        }
        $count = $query->count();
        $query->page($page, $limit)->order('id','desc');
        $lists = $query->select();
        foreach ($lists as $k=>$v) {
            $push_users = UsersService::getUsersFoundation($v['users_id']);
            $lists[$k]['nickname'] = $push_users['nickname'];
            $lists[$k]['avatar'] = $push_users['avatar'];
            $lists[$k]['picture'] = XypHelper::stringToArray($v['picture']);
            $lists[$k]['reply_picture'] = XypHelper::stringToArray($v['reply_picture']);
            $lists[$k]['status_text'] = ($v['status'] == 0?'未处理':($v['status'] == 1?'已处理':'已驳回'));
        }
        $this->success('请求成功',['total'=>$count,'data'=>$lists]);
    }

    public function appeal_submit(){
        $users = $this->getAuthUsers();
        if(!$agent_info = UsersService::getCommunityWhereUsersLocated($users->id)){
            $this->error('请先绑定社区');
        }
        $order_id = $this->request->param('id', 0);
        $content = $this->request->param('content', '');
        $picture = $this->request->param('picture', '');
        $status = $this->request->param('status', 1);
        $reject_reason = $this->request->param('reject_reason', '');
        $res = UsersAppeal::submitComplaintReply($order_id, $content, $picture,$status, $reject_reason);
        $this->success('处理成功');
    }
































































    public function index()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $user_id_array = (new AuthGroupAccess())->where([
            'group_id'=>(new AuthGroup())->where('name','like','%代理%')->value('id'),
        ])->column('uid');
        $this->_search_filter($where);
        $where['admin_id'] = array('in',$user_id_array);
        $data = $this->model->getList((new AdminBelong()),$where,'admin_id id,agent_area');
        $this->success('请求成功',$data);
    }

    /**
     * desc:代理个人中心
     */
    public function center_bak()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $users = $this->getAuthUsers();
        $param = $this->request->param();
        $bind_agent_id = (new AdminBelong())->where('bind_agent_user_id',$users->id)->value('admin_id');
        $user_id = $bind_agent_id;
        $walletsModel = new Wallets();
        $walletsInfo = $walletsModel->where(['user_id'=>$this->auth->id, 'type'=>'2', 'app_plat'=>$param['app_plat']])->find();
        $profitModel = new Profit();
        $orderReceiveModel = new OrderReceive();
        $where['agent_id'] = array('eq',$user_id);
        $where['app_plat'] = array('eq','MP-WEIXIN');
        $userReceiveApplyModel = new UserReceiveApply();
        $receive_id_array = $userReceiveApplyModel->where($where)->where('status', '1')->column('user_id');
        $map['receive_id'] = array('in',$receive_id_array);
        if(!$walletsInfo) {
            $total_income = 0.00;
            $can_withdrawal_amount = 0.00;
        } else {
            $total_income = $walletsInfo['total_income'];
            $can_withdrawal_amount = $walletsInfo['can_withdrawal_amount'];
        }

        $data = [
            'total_income'=>$total_income,
            'today_income'=>$profitModel->where($where)->whereTime('createtime', 'today')->sum('agent_profit'),
            'can_withdrawal_amount'=>$can_withdrawal_amount,
            'receiver_count'=>(new UserReceive())->where(['agent_id'=>$param['agent_id']])->where('status', 'normal')->count(),
            'week_income'=>$profitModel->where($where)->whereTime('createtime', 'week')->sum('agent_profit'),
            'week_finish_order_count'=>$orderReceiveModel->where('app_plat',$param['app_plat'])->where('status', '1')->where($map)->whereTime('createtime', 'week')->count(),
            'week_receive_count'=>$userReceiveApplyModel->where($where)->where('status', '1')->whereTime('updatetime', 'week')->count(),
//
            'month_income'=>$profitModel->where($where)->whereTime('createtime', 'month')->sum('agent_profit'),
            'month_finish_order_count'=>$orderReceiveModel->where('app_plat',$param['app_plat'])->where('status', '1')->where($map)->whereTime('createtime', 'month')->count(),
            'month_receive_count'=>$userReceiveApplyModel->where($where)->where('status', '1')->whereTime('updatetime', 'month')->count(),

            'year_income'=>$profitModel->where($where)->whereTime('createtime', 'year')->sum('agent_profit'),
            'year_finish_order_count'=>$orderReceiveModel->where('app_plat',$param['app_plat'])->where('status', '1')->where($map)->whereTime('createtime', 'year')->count(),
            'year_receive_count'=>$userReceiveApplyModel->where($where)->where('status', '1')->whereTime('updatetime', 'year')->count(),
        ];
        $this->success('请求成功',$data);
    }

    /**
     * desc:收入金额列表
     */
    public function profit_list()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $profitModel = new Profit();
        $where['agent_id'] = array('eq',(new AdminBelong())->where('bind_agent_user_id',$this->auth->id)->value('admin_id'));
        $where['app_plat'] = array('eq','MP-WEIXIN');
        $data = $profitModel->getList($profitModel,$where,'desc,createtime,agent_profit as receive_profit','id desc');
        $this->success('请求成功',$data);
    }

    /**
     * desc:接单员待提现金额
     */
    public function can_withdrawal_amount()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $walletsObj = (new Wallets())->where([
            'type'=>2,
            'user_id'=>$this->auth->id,
        ])->find();
        if(!$walletsObj) {
            $walletsObj['can_withdrawal_amount'] = 0;
        }
        $service_charge =$this->configObj->service_charge;
        $this->success('请求成功',['amount'=>$walletsObj['can_withdrawal_amount'],'service_charge'=>$service_charge]);
    }

    /**
     * desc接单员列表:
     */
    public function reveive_list()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $agent_id = (new AdminBelong())->where('bind_agent_user_id',$this->auth->id)->value('admin_id');

        $param = $this->request->param();
        $total = (new UserReceive())
            ->where([
                'agent_id'=>$agent_id,
                'app_plat'=>$param['app_plat'],
            ])->count();
        $data = (new UserReceive())
            ->where([
                'agent_id'=>$agent_id,
                'app_plat'=>$param['app_plat'],
            ])->order('id desc')
            ->page($param['page'],$param['limit'])
            ->field('user_id')
            ->select();

        $orderReceiveModel = new OrderReceive();
        $profitModel = new Profit();
        if(!empty($data)) {
            foreach ($data as $k=>$v) {
                $wechatInfo = (new UserPlat())->alias('plat')
                    ->where([
                        'plat.user_id'=>$v['user_id'],
                    ])
                    ->join('xyb_user_wechat wechat','plat.wechat_id = wechat.id')
                    ->field('wechat.avatar,wechat.nickname')->find();
                if($wechatInfo) {
                    $data[$k]['nickname'] = $wechatInfo['nickname'];
                    $data[$k]['avatar'] = XypHelper::xyb_full_url($wechatInfo->avatar);
                } else {
                    $openid = (new UserBelong())->where('user_id',$v['user_id'])->value('openid');
                    if(!$openid) {
                        $this->error('用户微信数据丢失');
                    }
                    $wechatObj = (new UserWechat())->where('openid',$openid)->find();
                    if($wechatObj) {
                        $data[$k]['nickname'] = $wechatObj['nickname'];
                        $data[$k]['avatar'] =XypHelper::xyb_full_url($wechatObj->avatar);
                    } else {
                        $this->error('用户微信数据丢失了');
                    }

                }

                $data[$k]['receive_count'] = $orderReceiveModel->where([
                    'receive_id'=>$v['user_id'],
                    'app_plat'=>$param['app_plat'],
                ])->count();
                $data[$k]['profit'] = $profitModel->where([
                    'receive_id'=>$v['user_id'],
                    'agent_id'=>$agent_id,
                ])->sum('agent_profit');
            }
        }

        $this->success('请求成功',[
            'total'=>$total,
            'data'=>$data,
        ]);
    }

    /**
     * desc:代理手机号
     */
    public function phone()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $agent_id = $this->request->param('agent_id');
        if (!$agent_id){
            $this->success('未选择学校');
        }else{
            $phone = (new AdminBelong())->where('admin_id',$agent_id)->value('phone');
            $this->success('请求成功',['phone'=>$phone]);
        }

    }

    /**
     * Desc  代理提交订阅
     * Create on 2024/5/29 14:55
     * Create by @小趴菜
     */
    public function submit_subscribe()
    {
        $count = 0;
        $subscribeObj = Db::name('xyb_agent_subscribe')->where('user_id', $this->auth->id)->where('type', 1)->find();
        if ($subscribeObj) {
            $count = Db::name('xyb_agent_subscribe')->where('user_id', $this->auth->id)->where('type', 1)->setInc('count');
        } else {
            $data = ['user_id' => $this->auth->id, 'count' => 1, 'type' => 1];
            $count = Db::name('xyb_agent_subscribe')->insert($data);
        }
        if ($count) {
            $this->success('订阅成功');
        } else {
            $this->error('订阅失败');
        }
    }

    /**
     * Desc  代理订阅数量
     * Create on 2024/5/29 14:55
     * Create by @小趴菜
     */
    public function subscribe_count()
    {
        $subscribeObj = Db::name('xyb_agent_subscribe')->where('user_id', $this->auth->id)->where('type', 1)->find();
        if ($subscribeObj) {
            $this->success('查询成功', ['subscribe_count' => $subscribeObj['count']]);
        } else {
            $this->success('查询成功', ['subscribe_count' => 0]);
        }
    }

}